package com.helloworld.demo.map;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

public class PersonTest {

    private static Unsafe unsafe;

    static {
        try {
            Field field = Unsafe.class.getDeclaredField("theUnsafe");
            field.setAccessible(true);
            unsafe = (Unsafe)field.get(null);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) throws NoSuchFieldException {

        final Person person = new Person();

        final long offset = unsafe.objectFieldOffset(Person.class.getDeclaredField("i"));

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    //person.i++;
                    boolean b = unsafe.compareAndSwapInt(person, offset, person.i, person.i + 1);
                    if(b){
                        //System.out.println(Thread.currentThread().getName() + person.i);
                        System.out.println(unsafe.getIntVolatile(person,offset));
                    } else{
                        System.out.println(Thread.currentThread().getName() + "CAS失败了");
                    }
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        },"Thread-1       ").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    //person.i++;
                    boolean b = unsafe.compareAndSwapInt(person, offset, person.i, person.i++);
                    if(b){
                        //System.out.println(Thread.currentThread().getName() + person.i);
                        System.out.println(unsafe.getIntVolatile(person,offset));
                    }else{
                        System.out.println(Thread.currentThread().getName() + "CAS失败了");
                    }

                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        },"Thread-2     ").start();

    }

}

class Person{
   volatile int i;
}
